import axios from 'axios'
import { MessageBox, Message } from 'element-ui' // eslint-disable-line

// story-create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60 * 1000, // request timeout
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type':'multipart/form-data'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    const logout = window.sessionStorage.getItem('logout') === 'true'

    if (res.code === 401) {
      if (!logout) {
        MessageBox({
          title: '提示',
          message: '你的登陆信息已失效，请点击前往登录后再回来操作保存，可避免录入信息丢失',
          type: 'error',
          showCancelButton: true,
          showConfirmButton: true,
          cancelButtonText: '关闭',
          confirmButtonText: '前往登录',
          closeOnPressEscape: false,
          duration: 5 * 1000
        }).then(() => {
          window.open('https://sso.yunjiglobal.com', '_blank')
        })

        window.sessionStorage.setItem('logout', 'true')

        return Promise.reject('你的登陆信息已失效，请点击前往登录后再回来操作保存，可避免录入信息丢失')
      }

      return res
    }
    if (logout) {
      // 当状态码返回不是401时  需要恢复退出的状态
      window.sessionStorage.setItem('logout', 'false')
    }

    if (res.code === 404) {
      // 路由跳转至未找到界面
      router.push('/404')
      return res
    }

    if (res.code === 9999) {
      Message({
        message: '系统内部异常，请联系管理员',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('系统内部异常，请联系管理员')
    }

    if (res.code === 8888) {
      return res
    }

    if (res.code !== 0) {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res.msg)
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      /* if (res.code === -100 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        })
      }*/
    }
    return res
  },
  error => {
    console.log(error) // for debug
    if (error.response.status === 401) {
      window.location.href = error.response.data.data.loginUrl
      return
    }
    if (error.response.status !== 200) {
      window.location.reload()
      return Promise.reject('网络错误，请刷新重试')
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
